<?php
	class Subject_chapter_model extends CI_Model{

		function __construct(){
			parent::__construct();
		}

		function get_chapter($subject_id){
			$result = array();

			$sql = "SELECT c.*, s.title AS sub_title,sc.title as top_title FROM {$this->db->dbprefix}b_subject_chapter AS c ";
			$sql .= " LEFT JOIN {$this->db->dbprefix}b_subject AS s ON(s.id=c.subject_id) ";
			$sql .= " LEFT JOIN {$this->db->dbprefix}b_subject_chapter AS sc ON(sc.id=c.parent_id) ";


			echo $sql .= " WHERE c.subject_id = $subject_id AND c.parent_id = 0";

			$top_chapter = $this->db->query($sql)->result_array();
			
			foreach ($top_chapter as $cha) {
				array_push($result,$cha);
				$chid = $this->get_chapter_by_parent($cha['id']);
				foreach ($chid as $ch) {
					array_push($result,$ch);
				}
			}
			return $result;
		}

		function get_chapter_by_parent($parent_id){
			$sql = "SELECT c.*, s.title AS sub_title,sc.title as top_title FROM {$this->db->dbprefix}b_subject_chapter AS c ";
			$sql .= " LEFT JOIN {$this->db->dbprefix}b_subject AS s ON(s.id=c.subject_id) ";
			$sql .= " LEFT JOIN {$this->db->dbprefix}b_subject_chapter AS sc ON(sc.id=c.parent_id) ";


			$sql .= " WHERE c.parent_id = $parent_id ";
			//$sql = "SELECT * FROM {$this->db->dbprefix}b_subject_chapter WHERE parent_id = $parent_id";
			return $this->db->query($sql)->result_array();
		}
	}